package com.scproject.scbef.service.user.impl;

import com.scproject.dto.ResponseDto;
import com.scproject.scbef.exception.ProcessException;
import com.scproject.scbef.mapper.ImgMapper;
import com.scproject.scbef.mapper.ImgRelationMapper;
import com.scproject.scbef.mapper.UserMapper;
import com.scproject.scbef.mapper.UserRoleMapper;
import com.scproject.scbef.mapper.expandmapper.UserLoginMapper;
import com.scproject.scbef.pojo.Img;
import com.scproject.scbef.pojo.ImgRelation;
import com.scproject.scbef.pojo.User;
import com.scproject.scbef.pojo.UserRole;
import com.scproject.scbef.pojo.expandenum.ImgTypeEnum;
import com.scproject.scbef.pojo.expandenum.UserRoleEnum;
import com.scproject.scbef.pojo.vo.ResponseCodeEnum;
import com.scproject.scbef.pojo.vo.UserLogin;
import com.scproject.scbef.pojo.vo.UserRoleVo;
import com.scproject.scbef.service.user.UserService;
import com.scproject.utils.*;
import com.scproject.utils.ProcessFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.scproject.utils.ProcessFileUtils.processFile;

/**
 * @author LNL
 * @date 2021/5/19 15:13
 */
@Service("userLoginService")
@Transactional
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserLoginMapper userLoginMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private ImgMapper imgMapper;
    @Autowired
    private ImgRelationMapper imgRelationMapper;

    @Override
    public ResponseDto login(UserLogin userLogin) {
        ResponseDto responseDto;
        Map<String, Object> transData = new HashMap<>();
        //逻辑：直接查询某个用户,通过username
        UserRoleVo userRoleVo = userLoginMapper.selectUserInfoByUserName(userLogin.getUsername());
        Optional<UserRoleVo> optionalUserRoleVo = Optional.ofNullable(userRoleVo);
        //如果不为空
        if (optionalUserRoleVo.isPresent()) {
            String password = userLogin.getPassword().trim();
            //转换为加密后的字符串
            String transPassword = MD5Util.getMD5(password);
            //密码正确
            if (transPassword.equals(userRoleVo.getPassword())) {
                //传输token，并且返回用户的基本信息，不包含用户名密码
                Map<String, String> userData = new HashMap<>();
                userData.put("userId", userRoleVo.getId());
                userData.put("name", userRoleVo.getName());
                String token = JWTUtils.generateToken(userData);
                //将用户名和密码置为空
                userRoleVo.setPassword("");
                transData.put("info", userRoleVo);
                transData.put("token", token);
                transData.put("roleType", userRoleVo.getRoleCode());
                responseDto = new ResponseDto(ResponseCodeEnum.SUCCESS.toString(), "登录成功", transData);
            } else {
                responseDto = new ResponseDto(ResponseCodeEnum.ERROR_PASSWORD.toString(), "登录失败,密码错误");
            }
        } else {
            responseDto = new ResponseDto(ResponseCodeEnum.ERROR_USER_NOT_EXISTS.toString(), "登录失败，用户名不存在");
        }

        return responseDto;
    }

    @Override
    public ResponseDto register(MultipartHttpServletRequest request) {
        ResponseDto responseDto = null;
        //注册,先处理二进制文件，再进行数据存储
//        Map<String,String> fileData = ProcessFileUtils.processFile(request);
        //说明文件处理成功
        try {
            Map<String, String[]> data = request.getParameterMap();
            User user = new User();
            user.setId(UUIDUtils.getUUID());
            user.setName(data.get("name")[0] == null ? "" : data.get("name")[0]);
            user.setEmail(data.get("email")[0] == null ? "" : data.get("email")[0]);
            user.setPhone(data.get("phone")[0] == null ? "" : data.get("phone")[0]);
            user.setScNumber(data.get("scNumber")[0] == null ? "" : data.get("scNumber")[0]);
            user.setPositions(data.get("positions")[0] == null ? "" : data.get("positions")[0]);
            user.setIntroduce(data.get("introduce")[0] == null ? "" : data.get("introduce")[0]);
            user.setUsername(data.get("username")[0] == null ? user.getScNumber() : data.get("username")[0]);
            user.setPassword(MD5Util.getMD5(data.get("password")[0] == null ? "123456" : data.get("password")[0]));

            //检验user是否已经存在
            boolean checkUserExists = checkUserExists(user.getUsername());
            //如果存在，直接驳回
            if (checkUserExists) {
                responseDto = new ResponseDto("1003", "用户名已存在");
                return responseDto;
            }

            //增加用户,isInsertUser是否成功
            int isInsertUser = userMapper.insertSelective(user);

            //查询普通用户的roleCode,对应的id
            String roleId = userLoginMapper.selectRoleId(UserRoleEnum.COMMON.toString());
            //添加用户关联
            UserRole userRole = new UserRole();
            userRole.setId(UUIDUtils.getUUID());
            userRole.setRoleId(roleId);
            userRole.setUserId(user.getId());
            int isInsertUserRole = userRoleMapper.insertSelective(userRole);

            if (isInsertUser > 0
                    && isInsertUserRole > 0) {
                //操作成功后，对文件进行上传
                List<MultipartFile> files = request.getFiles("file_transfer");
                for (MultipartFile file : files) {
                    Map<String, String> fileData = processFile(file);
                    //将图片存放到数据库中
                    Img img = new Img();
                    img.setId(UUIDUtils.getUUID());
                    img.setName(fileData.get("fileName"));
                    img.setPath(fileData.get("filePath"));

                    ImgRelation imgRelation = new ImgRelation();
                    imgRelation.setId(UUIDUtils.getUUID());
                    imgRelation.setImgId(img.getId());
                    imgRelation.setRelationId(user.getId());
                    imgRelation.setType(ImgTypeEnum.USER.toString());

                    int isInsertImg = imgMapper.insertSelective(img);
                    int isInsertImgRelation = imgRelationMapper.insertSelective(imgRelation);

                    if(isInsertImg > 0 && isInsertImgRelation > 0) {
                        responseDto = new ResponseDto("1000", "注册成功");
                    }else {
                        throw new ProcessException("注册失败");
                    }
                }
            } else {
                responseDto = new ResponseDto("1001", "注册失败");
            }
        } catch (Exception e) {
            throw new ProcessException("用户注册失败,后台服务器错误");
        }
        return responseDto;
    }

    //检验user是否存在
    public boolean checkUserExists(String username) {
        int count = userLoginMapper.selectUserByUserName(username);
        if (count > 0) {
            return true;
        }
        return false;
    }

}
